import React, { useEffect, useRef, useMemo } from "react";
import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  ScrollView,
  Alert,
} from "react-native";
import { Stack } from "expo-router";
import { useTheme } from "@/contexts/ThemeContext";
import { Ionicons, MaterialCommunityIcons } from "@expo/vector-icons";
import { getHeaderStyle } from "@/styles/header.style";
import { Button, Card, Divider, Badge, Switch, Icon } from "@rneui/themed";
import AsyncStorage from "@react-native-async-storage/async-storage";
import DateTimePicker from "@react-native-community/datetimepicker";

/**
 * 主题设置页面
 *
 * 允许用户点击卡片切换应用的深色/浅色主题或跟随系统设置
 */
export default function ThemeSettings() {
  // 获取当前主题模式和颜色
  const { themeMode, setThemeMode, colors, activeTheme } = useTheme();
  // 获取基于当前主题的header样式
  const headerStyles = getHeaderStyle(activeTheme);
  // 统一的颜色引用
  const primaryColor = colors.primary;
  const whiteColor = colors.text.white;
  const darkColor = "#15202B"; // 深色主题预览背景色

  // 自动切换状态
  const [autoChangeTime, setAutoChangeTime] = React.useState(false);
  const [startLightTime, setStartLightTime] = React.useState("07:00");
  const [startDarkTime, setStartDarkTime] = React.useState("19:00");

  // 时间选择状态
  const [showLightTimePicker, setShowLightTimePicker] = React.useState(false);
  const [showDarkTimePicker, setShowDarkTimePicker] = React.useState(false);

  // 加载和处理自动切换的设置
  useEffect(() => {
    const loadSettings = async () => {
      try {
        const autoChangeEnabled = await AsyncStorage.getItem(
          "@theme_auto_change"
        );
        if (autoChangeEnabled === "true") {
          setAutoChangeTime(true);
          const lightTime = await AsyncStorage.getItem("@theme_light_time");
          const darkTime = await AsyncStorage.getItem("@theme_dark_time");
          if (lightTime) setStartLightTime(lightTime);
          if (darkTime) setStartDarkTime(darkTime);
        }
      } catch (error) {
        console.error("Failed to load auto change settings:", error);
      }
    };

    loadSettings();
  }, []);

  // 实现根据时间自动切换主题的核心逻辑
  useEffect(() => {
    if (!autoChangeTime) return;

    const checkTimeAndSetTheme = () => {
      const now = new Date();
      const [lightHours, lightMinutes] = startLightTime.split(":").map(Number);
      const [darkHours, darkMinutes] = startDarkTime.split(":").map(Number);

      const lightTime = new Date();
      lightTime.setHours(lightHours, lightMinutes, 0, 0);

      const darkTime = new Date();
      darkTime.setHours(darkHours, darkMinutes, 0, 0);

      let targetMode: "light" | "dark";

      if (lightTime < darkTime) {
        // 白天长，黑夜短 (e.g., 07:00 -> 19:00)
        targetMode = now >= lightTime && now < darkTime ? "light" : "dark";
      } else {
        // 黑夜长，白天短 (e.g., 19:00 -> 07:00)
        targetMode = now >= darkTime && now < lightTime ? "dark" : "light";
      }

      if (themeMode !== targetMode) {
        setThemeMode(targetMode);
      }
    };

    // 立即执行一次检查
    checkTimeAndSetTheme();

    // 设置一个定时器，每分钟检查一次
    const interval = setInterval(checkTimeAndSetTheme, 60000);

    // 组件卸载或功能关闭时清除定时器
    return () => clearInterval(interval);
  }, [autoChangeTime, startLightTime, startDarkTime, setThemeMode, themeMode]);

  // 处理自动切换开关变化
  const handleAutoChangeToggle = async (value) => {
    setAutoChangeTime(value);
    try {
      await AsyncStorage.setItem(
        "@theme_auto_change",
        value ? "true" : "false"
      );
      if (value) {
        // 如果开启自动切换，则取消"跟随系统"
        if (themeMode === "system") {
          setThemeMode(activeTheme);
        }
        // 保存时间设置
        await AsyncStorage.setItem("@theme_light_time", startLightTime);
        await AsyncStorage.setItem("@theme_dark_time", startDarkTime);
      }
    } catch (error) {
      console.error("Failed to save auto change settings:", error);
    }
  };

  // 处理时间选择
  const handleTimeChange = async (event, selectedTime, isLightTime) => {
    setShowLightTimePicker(false);
    setShowDarkTimePicker(false);

    if (selectedTime) {
      // 格式化时间为 HH:MM 格式
      const hours = selectedTime.getHours().toString().padStart(2, "0");
      const minutes = selectedTime.getMinutes().toString().padStart(2, "0");
      const timeString = `${hours}:${minutes}`;

      if (isLightTime) {
        setStartLightTime(timeString);
        await AsyncStorage.setItem("@theme_light_time", timeString);
      } else {
        setStartDarkTime(timeString);
        await AsyncStorage.setItem("@theme_dark_time", timeString);
      }
    }
  };

  // 当用户手动选择主题时，如果自动切换已启用，则关闭它
  const handleThemeSelection = (newTheme) => {
    if (autoChangeTime && newTheme !== themeMode) {
      handleAutoChangeToggle(false);
    }
    setThemeMode(newTheme);
  };

  // 用于时间选择器的 Date 对象
  const timePickerDate = (timeString) => {
    const [hours, minutes] = timeString.split(":").map(Number);
    const date = new Date();
    date.setHours(hours, minutes);
    return date;
  };

  return (
    <>
      <Stack.Screen
        options={{
          title: "主题设置",
          headerTitleAlign: headerStyles.headerTitleAlign as "left" | "center",
          headerStyle: headerStyles.headerStyle,
          headerTintColor: headerStyles.headerTintColor,
          headerTitleStyle: headerStyles.headerTitleStyle,
        }}
      />
      <ScrollView
        style={[styles.container, { backgroundColor: colors.backgroundLight }]}
        contentContainerStyle={styles.contentContainer}
      >
        {/* 主题选择卡片 */}
        <View style={[styles.card, { backgroundColor: colors.background }]}>
          <Text style={[styles.cardTitle, { color: colors.text.primary }]}>
            外观
          </Text>
          <Text style={[styles.instruction, { color: colors.text.secondary }]}>
            选择您喜欢的显示模式
          </Text>
          <View style={styles.themeModeContainer}>
            {/* 浅色模式选项 */}
            <TouchableOpacity
              style={[
                styles.themeModeOption,
                themeMode === "light" && [
                  styles.selectedMode,
                  { borderColor: primaryColor },
                ],
                { backgroundColor: whiteColor },
              ]}
              activeOpacity={0.7}
              onPress={() => handleThemeSelection("light")}
            >
              <View
                style={[styles.themePreview, { backgroundColor: whiteColor }]}
              >
                <View style={styles.previewHeader}>
                  <View
                    style={[
                      styles.previewIcon,
                      { backgroundColor: primaryColor },
                    ]}
                  />
                </View>
                <View style={styles.previewContent}>
                  <View
                    style={[
                      styles.previewText,
                      { backgroundColor: colors.inputBackground, width: "80%" },
                    ]}
                  />
                  <View
                    style={[
                      styles.previewText,
                      { backgroundColor: colors.inputBackground, width: "60%" },
                    ]}
                  />
                </View>
              </View>
              <Text
                style={[styles.themeModeText, { color: colors.text.primary }]}
              >
                浅色
              </Text>
              {themeMode === "light" && (
                <View style={styles.checkMark}>
                  <Ionicons
                    name="checkmark-circle"
                    size={24}
                    color={primaryColor}
                  />
                </View>
              )}
            </TouchableOpacity>

            {/* 深色模式选项 */}
            <TouchableOpacity
              style={[
                styles.themeModeOption,
                themeMode === "dark" && [
                  styles.selectedMode,
                  { borderColor: primaryColor },
                ],
                {
                  backgroundColor: darkColor,
                },
              ]}
              activeOpacity={0.7}
              onPress={() => handleThemeSelection("dark")}
            >
              <View
                style={[styles.themePreview, { backgroundColor: darkColor }]}
              >
                <View style={styles.previewHeader}>
                  <View
                    style={[
                      styles.previewIcon,
                      { backgroundColor: primaryColor },
                    ]}
                  />
                </View>
                <View style={styles.previewContent}>
                  <View
                    style={[
                      styles.previewText,
                      {
                        backgroundColor: "#38444D",
                        width: "80%",
                      },
                    ]}
                  />
                  <View
                    style={[
                      styles.previewText,
                      {
                        backgroundColor: "#38444D",
                        width: "60%",
                      },
                    ]}
                  />
                </View>
              </View>
              <Text style={[styles.themeModeText, { color: whiteColor }]}>
                深色
              </Text>
              {themeMode === "dark" && (
                <View style={styles.checkMark}>
                  <Ionicons
                    name="checkmark-circle"
                    size={24}
                    color={primaryColor}
                  />
                </View>
              )}
            </TouchableOpacity>
          </View>

          {/* 跟随系统选项 */}
          <TouchableOpacity
            style={[
              styles.systemOptionCard,
              themeMode === "system" && [
                styles.selectedMode,
                { borderColor: primaryColor },
              ],
              {
                backgroundColor: colors.backgroundHighlight,
              },
            ]}
            activeOpacity={0.7}
            onPress={() => handleThemeSelection("system")}
          >
            <View style={styles.systemOptionContent}>
              <MaterialCommunityIcons
                name="theme-light-dark"
                size={24}
                color={
                  themeMode === "system" ? primaryColor : colors.text.secondary
                }
                style={{ marginRight: 12 }}
              />
              <View>
                <Text
                  style={[
                    styles.systemOptionTitle,
                    { color: colors.text.primary },
                  ]}
                >
                  跟随系统
                </Text>
                <Text
                  style={[
                    styles.systemOptionDescription,
                    { color: colors.text.secondary },
                  ]}
                >
                  自动根据系统设置切换主题
                </Text>
              </View>
            </View>
            {themeMode === "system" && (
              <View style={styles.checkMarkSystem}>
                <Ionicons
                  name="checkmark-circle"
                  size={24}
                  color={primaryColor}
                />
              </View>
            )}
          </TouchableOpacity>
        </View>

        {/* 高级设置卡片 */}
        <View style={[styles.card, { backgroundColor: colors.background }]}>
          <Text style={[styles.cardTitle, { color: colors.text.primary }]}>
            高级设置
          </Text>

          <View style={styles.settingRow}>
            <View style={styles.settingTextContainer}>
              <Text
                style={[styles.settingTitle, { color: colors.text.primary }]}
              >
                根据时间自动切换
              </Text>
              <Text
                style={[
                  styles.settingDescription,
                  { color: colors.text.secondary },
                ]}
              >
                白天使用浅色模式，夜间使用深色模式
              </Text>
            </View>
            <Switch
              value={autoChangeTime}
              onValueChange={handleAutoChangeToggle}
              trackColor={{ false: "#767577", true: primaryColor }}
              thumbColor={autoChangeTime ? "#ffffff" : "#f4f3f4"}
            />
          </View>

          {autoChangeTime && (
            <View style={styles.timeSettingsContainer}>
              <TouchableOpacity
                style={styles.timeSettingRow}
                onPress={() => setShowLightTimePicker(true)}
              >
                <Text style={{ color: colors.text.primary }}>
                  浅色模式开始时间
                </Text>
                <Text style={styles.timeValueText}>{startLightTime}</Text>
              </TouchableOpacity>
              <Divider style={{ marginVertical: 10 }} />
              <TouchableOpacity
                style={styles.timeSettingRow}
                onPress={() => setShowDarkTimePicker(true)}
              >
                <Text style={{ color: colors.text.primary }}>
                  深色模式开始时间
                </Text>
                <Text style={styles.timeValueText}>{startDarkTime}</Text>
              </TouchableOpacity>
            </View>
          )}

          {/* 时间选择器 */}
          {showLightTimePicker && (
            <DateTimePicker
              value={timePickerDate(startLightTime)}
              mode="time"
              is24Hour={true}
              display="default"
              onChange={(event, selectedTime) =>
                handleTimeChange(event, selectedTime, true)
              }
            />
          )}
          {showDarkTimePicker && (
            <DateTimePicker
              value={timePickerDate(startDarkTime)}
              mode="time"
              is24Hour={true}
              display="default"
              onChange={(event, selectedTime) =>
                handleTimeChange(event, selectedTime, false)
              }
            />
          )}
        </View>

        {/* 说明卡片 */}
        <View style={[styles.card, { backgroundColor: colors.background }]}>
          <Text style={[styles.description, { color: colors.text.secondary }]}>
            深色模式可以减轻眼睛疲劳，在弱光环境下使用效果更佳。跟随系统将根据设备的设置自动调整。
          </Text>

          {autoChangeTime && (
            <View style={styles.tipContainer}>
              <Ionicons
                name="information-circle-outline"
                size={20}
                color={colors.primary}
                style={{ marginRight: 8 }}
              />
              <Text style={[styles.tipText, { color: colors.text.secondary }]}>
                已开启自动切换：每天 {startLightTime} 切换到浅色模式，
                {startDarkTime} 切换到深色模式。
              </Text>
            </View>
          )}
        </View>
      </ScrollView>
    </>
  );
}

// 样式表
const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  contentContainer: {
    paddingBottom: 24,
  },
  card: {
    padding: 20,
    marginVertical: 8,
    marginHorizontal: 16,
    borderRadius: 16,
    shadowColor: "rgba(0, 0, 0, 0.08)",
    shadowOffset: { width: 0, height: 4 },
    shadowOpacity: 1,
    shadowRadius: 10,
    elevation: 3,
  },
  cardTitle: {
    fontSize: 20,
    fontWeight: "bold",
    marginBottom: 8,
  },
  instruction: {
    fontSize: 14,
    marginBottom: 20,
  },
  themeModeContainer: {
    flexDirection: "row",
    justifyContent: "space-between",
  },
  themeModeOption: {
    width: "48%",
    borderRadius: 12,
    borderWidth: 2,
    borderColor: "transparent",
    padding: 12,
    alignItems: "center",
    position: "relative",
  },
  selectedMode: {
    borderWidth: 3,
  },
  themePreview: {
    width: "100%",
    height: 100,
    borderRadius: 8,
    overflow: "hidden",
    marginBottom: 12,
    borderWidth: 1,
    borderColor: "rgba(0,0,0,0.1)",
  },
  previewHeader: {
    height: 30,
    padding: 8,
    alignItems: "flex-start",
  },
  previewIcon: {
    width: 16,
    height: 16,
    borderRadius: 8,
  },
  previewContent: {
    padding: 8,
  },
  previewText: {
    height: 8,
    borderRadius: 4,
    marginBottom: 8,
  },
  themeModeText: {
    fontSize: 16,
    fontWeight: "500",
  },
  checkMark: {
    position: "absolute",
    top: 8,
    right: 8,
  },
  checkMarkSystem: {
    position: "absolute",
    top: "50%",
    right: 16,
    transform: [{ translateY: -12 }],
  },
  systemOptionCard: {
    width: "100%",
    marginTop: 16,
    borderRadius: 12,
    borderWidth: 2,
    borderColor: "transparent",
    paddingVertical: 16,
    paddingHorizontal: 20,
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    position: "relative",
  },
  systemOptionContent: {
    flexDirection: "row",
    alignItems: "center",
  },
  systemOptionTitle: {
    fontSize: 16,
    fontWeight: "500",
  },
  systemOptionDescription: {
    fontSize: 12,
    marginTop: 4,
  },
  description: {
    fontSize: 14,
    lineHeight: 22,
  },
  settingRow: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    paddingVertical: 10,
  },
  settingTextContainer: {
    flex: 1,
    marginRight: 16,
  },
  settingTitle: {
    fontSize: 16,
    fontWeight: "500",
  },
  settingDescription: {
    fontSize: 12,
    marginTop: 4,
    lineHeight: 18,
  },
  timeSettingsContainer: {
    backgroundColor: "rgba(0,0,0,0.03)",
    borderRadius: 10,
    marginTop: 10,
    paddingHorizontal: 15,
  },
  timeSettingRow: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    paddingVertical: 15,
  },
  timeValueText: {
    fontSize: 16,
    fontWeight: "500",
  },
  tipContainer: {
    flexDirection: "row",
    alignItems: "center",
    marginTop: 16,
    padding: 10,
    borderRadius: 8,
    backgroundColor: "rgba(0,0,0,0.03)",
  },
  tipText: {
    flex: 1,
    fontSize: 13,
    lineHeight: 18,
  },
});
